package com.thread.example.config;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;

/**
 * @author guoQ.z
 * @date 2021/1/27 17:38
 * TODO
 */
public class ThreadPoolConfig {

    public static ExecutorService buildThreadPool() {
        // 自己实现 ThreadFactory
        ThreadFactory threadFactory = new MyThreadFactory("async-thread-");

        return new ThreadPoolExecutor(10, 20, 0,
                TimeUnit.SECONDS, new LinkedBlockingDeque<>(50), threadFactory, new ThreadPoolExecutor.CallerRunsPolicy());
    }

    public static ExecutorService buildThreadPool(Integer corePoolSize, Integer maxPoolSize, Integer queueSize, String threadNamePrefix) {
        /**
         * <!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
         *         <dependency>
         *             <groupId>com.google.guava</groupId>
         *             <artifactId>guava</artifactId>
         *             <version>28.1-jre</version>
         *         </dependency>
         */
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(threadNamePrefix).build();

        return new ThreadPoolExecutor(corePoolSize, maxPoolSize, 0,
                TimeUnit.SECONDS, new LinkedBlockingDeque<>(queueSize), threadFactory, new ThreadPoolExecutor.CallerRunsPolicy());
    }
}
